import { getEstateInfo, submit, labelQueryList, queryAllAddress, update, queryItem } from './baseinfoDetailServ.js'
// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, _ } from 'lodash'
import { hashHistory } from 'dva/router';
import { makeAddress } from "utils/util"
import AppBus from 'utils/bus'
let sellerQueryList = [
  {
    name: '系统类型', type: 'select', key: 'appId', value:2, notNeedAll: true, list: [
      // {id: '1', name: '旧系统'},
      {id: '2', name: '新系统'},
    ]
  },
  { name: '工程名称', type: 'text', key: 'name', value: '' },
  // { name: '省市', type: 'cascader', list: areaList, key: ['province','city','county'], value: '' },
]
// 初始默认状态
const state = {
  sellerQueryList: cloneDeep(sellerQueryList),//选择工程弹窗搜索
  btnLoading: false,//发布按钮loading
  tagALL: [],//标签
  video: [],
  fileList: [],
  previewVisible: false,
  previewImage: "",
  Mapmodel: false,//地图弹出框
  saleMapmodel: false,
  showModel: false,
  sellerList: [],//工程选择
  house720: '',
  vr: '',
  subElements:[],
  estateInfo: {
    latAndLon: [],//经纬度['plan', 'effect', 'realScene', 'periphery', 'poster','building']
    saleLatAndLon: [],//经纬度['plan', 'effect', 'realScene', 'periphery', 'poster','building']
    mapAddress: '',//地图位置
    name: '',
    appId: '1',//1:旧系统，2：新系统
    smallimg:[],
    plan: [],
    effect: [],
    realScene: [],
    periphery: [],
    poster: [],
    building: [],
    videoImageFiles: [],
    visitMinHours:'2',
    longestTime:'',
    bufferDays:"0",
    transactionInvalidDays:'30',
    isTransferProperty:0
  },
  imageUrls:[],
  tag: [],
  actionType: '',
  areaList: [],
  disabled: false,
  tagModel: false,
  min:120,
  min2:0
}
// 整理后端格式
function makeJson(busiType, fileType, fileUrl) {
  return {
    busiType,
    fileType,
    fileUrl
  }
}
function makedefult(data){
 
  return data
}

const tmpModule = {
  namespace: 'baseDetailModel',
  state: cloneDeep(state),
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        let { actionType, productId } = query
        if ('' + tmpModule.pathname === '' + pathname) {
          //每次进来页面更新数据 重置state
          dispatch({ type: 'updateStore', payload: cloneDeep(state) });
          dispatch({ type: 'updateStore', payload: { actionType, productId } });
          dispatch({ type: 'getLabelQueryList', payload: { type: 1, pageSize: 1003 } });
          dispatch({ type: 'getAreaList', payload: {} });
          dispatch({ type: 'getSubElements', payload: {} });
          if (actionType == 'edit') {
            dispatch({ type: 'estateInfo', payload: { productId, actionType } });
          } else if (actionType == 'check') {
            dispatch({ type: 'estateInfo', payload: { productId, actionType } });
          }
        }
      })
    },
  },
  effects: {
    *estateInfo({ payload }, { put, call, select }) {
      
      try {
        let { productId } = payload
        let {sellerQueryList} = yield select(state => state[tmpModule.namespace])
        console.log(888)
        //测试数据"1044937259600064512"
        const { data, success} = yield call(getEstateInfo, { productId })
        if(success){
          //console.log(data)
          let list={
            projectCode:data.projectCode,
            name:data.projectName,
            projectId:data.projectId,
          }
          let sellerList=[]
          sellerList.push(list)
          
          data.medias && Object.keys(data.medias).map((item, idx) => {
            data[item] = data.medias[item]
          })
          delete data.medias

          //处理video地址
          let newVideo = []
          if(data.video){
            data.video.map((item,index)=>{
              console.log(item,index)
              let VideoObj = {
                url:item,
                name:item
              }
              newVideo.push(VideoObj)
            })
            data.video=newVideo
          }
          //处理voice地址
          let newVoice = []
          if(data.voice){
            data.voice.map((item,index)=>{
              console.log(item,index)
              let VoiceObj = {
                url:item,
                name:item
              }
              newVoice.push(VoiceObj)
            })
            data.voice=newVoice
          }

          //整理后端数据
          let video = ['house720', 'vr']
          Object.keys(data).map((item, idx) => {
            if (video.indexOf(item) > -1) {
              data[item] = data[item][0]
            }
          })
          data.latAndLon = []
          data.saleLatAndLon = []
          data.saleLatAndLon[0] = data.saleAddressLng
          data.saleLatAndLon[1] = data.saleAddressLat
          data.latAndLon[0] = data.longitude
          data.latAndLon[1] = data.latitude
          data.appId = data.outerApp||'1'
          // data.appId = "1"
          sellerQueryList.map((item,index)=>{
            if(item.key=='appId'){
             item.value= data.appId
            }
          })
          data.bindCity = [data.province, data.city, data.county]
          let min = (data.visitMinHours*60).toFixed(2)
          if(data.longestTime){
          var min2 = (data.longestTime*60).toFixed(2)
          }

            // 有字段
          if(data.effect&&data.effect.length > 0 && data.smallimg&&data.smallimg.length === 0) {
              data.smallimg = []
              data.smallimg.push(data.effect[0])
              // const { data, resultCode, resultMsg } = yield call(getEstateInfo, { productId })
              // data.effect.shift()
          }
          if (!!data.saleAddressLng || !!data.saleAddressLat) {
            data.saleMapAddress = data.saleAddress
          }
          yield put({ type: 'updateStore', payload: { estateInfo: data ,sellerQueryList,min,min2,sellerList} });
        }
        
      } catch (e) {
        console.log(e)
      }
    },
    *getLabelQueryList({ payload }, { put, call, select }) {
      try {
        const { rows } = yield call(labelQueryList, payload)
        yield put({ type: 'updateStore', payload: { tagALL: rows } });
      } catch (e) {
        console.log(e)
      }
    },
    *getAreaList({ payload }, { put, call, select }) {
      try {
        const data = yield call(queryAllAddress, {})
        if (data.success) {
          let areaList = []
          //澳门与北京只有两级
          let arr = [data.data[0]]
          let attr = [data.data[data.data.length - 1]]
          data.data[0] = {
            label: "北京",
            value: "110100",
            children: arr
          }
          data.data[data.data.length - 1] = {
            label: "澳门",
            value: "820000",
            children: attr
          }
          areaList = data.data

          yield put({ type: 'updateStore', payload: { areaList } });
        }
      } catch (e) {

      }
    },
    *getSubElements({ payload }, { put }){
      let { subElements } = JSON.parse(localStorage.getItem('navBar'));
      yield put({ type: 'updateStore', payload: { subElements } });
    },
    *queryItem({ payload }, { put, call, select }) {
      try {
        let tmpState = yield select(state => state[tmpModule.namespace])
        let { estateInfo,productId } = tmpState
        let { projectCode, projectId, appId = "1" } = payload
        let params = {

        }

        if (estateInfo.appId == 2 ) {
          params.projectCode = projectId || ''
        } else {
          params.projectCode = projectCode
        }
        console.log(productId)
        const { data, success } = yield call(queryItem, { ...params, appId,productId })
        if (success) {
          data && Object.keys(data).map((item, idx) => {
            if (!estateInfo[item] || (estateInfo[item] && estateInfo[item].length == 0)) {
              estateInfo[item] = data[item]
            }
          })
          estateInfo.projectName = data.name
          estateInfo.outerId = data.projectId
          estateInfo.projectId = data.projectId
          estateInfo.projectCode = data.projectCode
          estateInfo.latAndLon = [data.longitude, data.latitude]
          yield put({ type: 'updateStore', payload: { estateInfo,showModel:false} });
        }
      } catch (e) {
        console.log(e)
      }
    },
    
    *sumbit({ payload }, { put, call, select }) {
      try {
        let tmpState = yield select(state => state[tmpModule.namespace])
        let { estateInfo } = tmpState
        //yield put({ type: 'updateStore', payload: { disabled:true } });
        let key = ['smallimg','plan', 'effect', 'realScene', 'periphery', 'poster', 'building', 'videoImageFiles','appPhoto']
        let video = ['video', 'house720', 'vr']
        estateInfo.medias = []
        // if(estateInfo.smallimg.length==0){
        //   delete estateInfo.smallimg
        // }
        //视频图片循环
        //图片循环

        for (var i = 0; i < key.length; i++) {
          if (estateInfo[key[i]] && estateInfo[key[i]].length > 0) {
            for (var j = 0; j < estateInfo[key[i]].length; j++) {
              if (key[i] == 'videoImageFiles') {
                estateInfo.medias.push(makeJson(key[i], 1, estateInfo[key[i]][j][0]))
              } else {
                estateInfo.medias.push(makeJson(key[i], 1, estateInfo[key[i]][j]))
              }
            }
          }
        }
        //视频循环
        
        if(estateInfo.video){
          let newVideoArr = []
          estateInfo.video.map((item,index)=>{
            console.log(item)
            newVideoArr.push(item.url)
          })
          estateInfo.video = newVideoArr
        }
        //音频循环
        
        if(estateInfo.voice){
          let newVoiceArr = []
          estateInfo.voice.map((item,index)=>{
            console.log(item)
            newVoiceArr.push(item.url)
          })
          estateInfo.voice = newVoiceArr
        }
        

        for (var i = 0; i < video.length; i++) {
          if (i == 0 || i ==3) {
            if (estateInfo[video[i]] && estateInfo[video[i]].length > 0) {
              for (var j = 0; j < estateInfo[video[i]].length; j++) {
                estateInfo.medias.push(makeJson(video[i], 2, estateInfo[video[i]][j]))
              }
            } else {
              //最后一种情况（清空 还要传多一条东西）
              estateInfo.medias.push(makeJson(video[i], 2, ""))
            }

          } else {
            if (estateInfo[video[i]] && estateInfo[video[i]].length > 0) {
              estateInfo.medias.push(makeJson(video[i], 2, estateInfo[video[i]]))
            } else {
              //最后一种情况（清空 还要传多一条东西）
              estateInfo.medias.push(makeJson(video[i], 2, estateInfo[video[i]]))
            }
          }
        }


        console.log(estateInfo.medias)
        //所属城市
        if (estateInfo.bindCity.length == 2) {
          let data = ['city', 'county']
          for (var i = 0; i < 2; i++) {
            estateInfo[data[i]] = estateInfo.bindCity[i]
          }
          estateInfo.province = estateInfo.city
        } else {
          let data = ['province', 'city', 'county']
          for (var i = 0; i < 3; i++) {
            estateInfo[data[i]] = estateInfo.bindCity[i]
          }
        }
        // //删除冗余数据
        // for (var i = 0; i < key.length; i++) {
        //   delete estateInfo[key[i]]
        // }
        //区数
        if (!estateInfo.zone) {
          estateInfo.zone = 0
        }
        if (estateInfo.shelfStatus == 1 && estateInfo.effect && estateInfo.effect.length == 0) {
          message.warning('请上传效果图')
          return false
        }
        if (estateInfo.shelfStatus == 1 && estateInfo.smallimg && estateInfo.smallimg.length == 0) {
          message.warning('请上传缩略图')
          return false
        }
        
        // if (!estateInfo.outerId) {
        //   message.warn('请选择工程名')
        //   return
        // }

        // if(!estateInfo.visitMinHours ){
        //   message.warn('请输入报备到访最短有效时间')
        //   return
        // }
        // if(!estateInfo.transactionInvalidDays ){
        //   message.warn('请输入成交失效时长（天）')
        //   return
        // }
        estateInfo.longitude = estateInfo.latAndLon && estateInfo.latAndLon[0]
        estateInfo.latitude = estateInfo.latAndLon && estateInfo.latAndLon[1]
        estateInfo.saleAddressLng = estateInfo.saleLatAndLon && estateInfo.saleLatAndLon[0]
        estateInfo.saleAddressLat = estateInfo.saleLatAndLon && estateInfo.saleLatAndLon[1]
        estateInfo.outerApp = estateInfo.appId
        
         if(estateInfo&&estateInfo.openingTime==""){
          delete estateInfo.openingTime
        }
        yield put({type: 'updateStore', payload: {loading: true, btnLoading: true,}})
        //编辑或新增
        if (tmpState.actionType == 'add') {
          const data = yield call(submit, estateInfo)
          yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
          if (data.success) {
            //yield put({ type: 'updateStore', payload: { disabled:false } });
            message.success('提交成功').then(() => {
              // hashHistory.push({pathname: '/home/buildingAdmin/baseinfo'})
              let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
              AppBus.emit('closeTab', {
                key: urlArray[0],
                cbf: () => {
                  hashHistory.push(urlArray[1])
                }
              })
            });
          }
        } else {
          estateInfo.productId = tmpState.productId
          const data = yield call(update, estateInfo)
          yield put({type: 'updateStore', payload: {loading: false, btnLoading: false,}})
          if (data.success) {
            message.success('编辑成功').then(() => {
              let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
              AppBus.emit('closeTab', {
                key: urlArray[0],
                cbf: () => {
                  hashHistory.push(urlArray[1])
                }
              })
            });
          } else {
            //yield put({ type: 'updateStore', payload: { disabled:false } });
          }
        }


      } catch (e) {
        console.log(e)
      }
    },
    *updateModel({ payload }, { put, select }) {
      yield put({ type: 'updateStore', payload });
    },
  },
  reducers: {
    updateStore(preState, action) {
      return { ...preState, ...action.payload };
    }
  }
}

export default tmpModule
